<template>
  <div class="user-orders">
    <el-card class="order-card">
      <template #header>
        <div class="card-header">
          <h3>我的订单</h3>
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="全部订单" name="all" />
            <el-tab-pane label="待付款" name="unpaid" />
            <el-tab-pane label="已支付" name="paid" />
            <el-tab-pane label="已发货" name="shipped" />
            <el-tab-pane label="已完成" name="completed" />
            <el-tab-pane label="已取消" name="cancelled" />
          </el-tabs>
        </div>
      </template>

      <!-- 订单列表 -->
      <div class="order-list" v-loading="loading">
        <el-empty v-if="!orderList.length" description="暂无相关订单" />
        <div v-else class="order-item" v-for="order in orderList" :key="order.id">
          <div class="order-header">
            <span class="order-time">下单时间：{{ formatDate(order.createTime) }}</span>
            <span class="order-number">订单号：{{ order.orderNumber }}</span>
            <div class="order-status-group">
              <span class="order-status">{{ getStatusText(order.status) }}</span>
            </div>
          </div>
          <div class="order-content">
            <!-- 商品列表预览 -->
            <div class="product-preview" @click="toggleOrderDetail(order.id)">
              <div class="product-info">
                <div class="product-names" :title="order.products.map(p => p.name).join(' / ')">
                  {{ order.products.map(p => p.name).join(' / ').length > 50 
                     ? order.products.map(p => p.name).join(' / ').substring(0, 50) + '...' 
                     : order.products.map(p => p.name).join(' / ') 
                  }}
                </div>
                <div class="preview-more" v-if="order.products && order.products.length > 1">
                  共{{ order.products.length }}件商品
                </div>
              </div>
            </div>

            <!-- 展开的订单详情 -->
            <el-collapse-transition>
              <div v-show="expandedOrderId === order.id" class="order-detail">
                <div class="product-list">
                  <div class="product-item" v-for="product in order.products" :key="product.id">
                    <el-image :src="product.image" :alt="product.name" class="product-image" />
                    <div class="product-info">
                      <h4>{{ product.name }}</h4>
                      <div class="product-price">
                        <span class="price">¥{{ product.price }}</span>
                        <span class="count">x{{ product.count }}</span>
                        <span class="total-price">小计：¥{{ product.totalPrice }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="order-summary">
                  <div class="summary-item">
                    <span>商品总额：</span>
                    <span>¥{{ order.itemAmount }}</span>
                  </div>
                  <div class="summary-item">
                    <span>运费：</span>
                    <span>¥{{ order.freightAmount }}</span>
                  </div>
                  <div class="summary-item">
                    <span>优惠金额：</span>
                    <span>¥{{ order.discountAmount }}</span>
                  </div>
                  <div class="summary-item total">
                    <span>实付金额：</span>
                    <span class="amount">¥{{ order.totalAmount }}</span>
                  </div>
                </div>
              </div>
            </el-collapse-transition>

            <div class="order-footer">
              <div class="total-amount">
                实付金额：<span class="amount">¥{{ order.totalAmount }}</span>
              </div>
              <div class="order-actions">
                <el-button 
                  v-if="order.status === 'unpaid'" 
                  type="primary"
                  @click="handlePay(order)"
                >
                  立即付款
                </el-button>
                <el-button 
                  v-if="order.status === 'completed'" 
                  @click="handleReview(order)"
                >
                  评价
                </el-button>
                <el-button 
                  v-if="order.status === 'shipped'" 
                  type="success"
                  @click="handleConfirmReceive(order)"
                >
                  确认收货
                </el-button>
                <el-button @click="toggleOrderDetail(order.id)">
                  <el-icon><ArrowDown v-if="expandedOrderId !== order.id" /><ArrowUp v-else /></el-icon>
                  {{ expandedOrderId === order.id ? '收起详情' : '展开详情' }}
                </el-button>
                <el-button @click="handleOrderDetail(order)">查看详情</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getOrderList as fetchOrderList, getOrdersByStatus, shipOrder, finishOrder } from '@/api/order'
import { useUserStore } from '@/stores/modules/user'
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 状态数据
const loading = ref(false)
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const orderList = ref([])

// 获取订单列表
// 转换订单数据格式
const transformOrderData = (orders) => {
  if (!Array.isArray(orders)) {
    console.error('订单数据格式错误：', orders)
    return []
  }

  const statusMap = {
    0: 'unpaid',    // 待支付
    1: 'paid',      // 已支付
    2: 'shipped',   // 已发货
    3: 'completed', // 已完成
    4: 'cancelled'  // 已取消
  }

  const paymentStatusMap = {
    0: 'unpaid',    // 未支付
    1: 'paid',      // 已支付
    2: 'refunded'   // 已退款
  }
  
  return orders.map(order => ({
    id: order.id,
    orderNumber: order.orderNo,
    status: statusMap[order.status] || 'unknown',
    paymentStatus: paymentStatusMap[order.paymentStatus] || 'unknown',
    totalAmount: order.payAmount.toFixed(2),
    itemAmount: order.itemAmount.toFixed(2),
    freightAmount: order.freightAmount.toFixed(2),
    discountAmount: order.discountAmount.toFixed(2),
    paymentType: order.paymentType,
    paymentTime: order.paymentTime,
    createTime: order.createTime,
    products: (order.orderItemList || []).map(item => ({
      id: item.skuId,
      name: item.itemName,
      image: item.itemImage,
      price: item.price.toFixed(2),
      count: item.quantity,
      totalPrice: item.totalPrice.toFixed(2)
    }))
  }))
}

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    unpaid: '待付款',
    paid: '已支付',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 在获取订单列表的代码中也需要修改状态映射
const getOrderList = async () => {
  loading.value = true
  try {
    

    let res
    if (activeTab.value === 'all') {
      // 获取所有订单
      res = await fetchOrderList({
        page: currentPage.value,
        pageSize: pageSize.value
      })
    } else {
      // 根据状态获取订单
      const statusMap = {
        'unpaid': 0,    // 待支付
        'paid': 1,      // 已支付
        'shipped': 2,   // 已发货
        'completed': 3, // 已完成
        'cancelled': 4  // 已取消
      }
      res = await getOrdersByStatus(statusMap[activeTab.value])
    }

    if (res && Array.isArray(res)) {
      orderList.value = transformOrderData(res)
      total.value = res.length
    } else {
      orderList.value = []
      total.value = 0
    }

  } catch (error) {
    console.error('获取订单列表失败：', error)
    ElMessage.error('获取订单列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  try {
    // 将日期字符串转换为本地时间
    const localDate = new Date(date)
    return localDate.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })
  } catch (error) {
    console.error('日期格式化失败：', error)
    return '日期格式错误'
  }
}

// 事件处理方法
const handleTabClick = (tab) => {
  // 直接使用tab.props.name作为新的状态值
  activeTab.value = tab.props.name
  currentPage.value = 1
  getOrderList()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getOrderList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getOrderList()
}

const handlePay = async (order) => {
  try {
    // 检查用户是否已登录
    if (!userStore.isLoggedIn || !userStore.accessToken) {
      ElMessage.warning('请先登录')
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.value.fullPath }
      })
      return
    }
    
    // 跳转到支付页面
    router.push({
      path: '/payment',
      query: {
        id: order.id,
        method: 'alipay'  // 默认使用支付宝支付
      }
    })
  } catch (error) {
    console.error('支付失败：', error)
    ElMessage.error('支付失败，请稍后重试')
  }
}

const handleConfirmReceive = (order) => {
  ElMessageBox.confirm('确认已收到商品？', '确认收货', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 检查用户是否已登录
      if (!userStore.isLoggedIn || !userStore.accessToken) {
        ElMessage.warning('请先登录')
        router.push({
          path: '/login',
          query: { redirect: router.currentRoute.value.fullPath }
        })
        return
      }
      
      // 调用确认收货接口
      await finishOrder(order.id)
      ElMessage.success('确认收货成功')
      getOrderList()
    } catch (error) {
      console.error('确认收货失败：', error)
      ElMessage.error('确认收货失败，请重试')
    }
  })
}

const handleReview = (order) => {
  // 检查用户是否已登录
  if (!userStore.isLoggedIn || !userStore.accessToken) {
    ElMessage.warning('请先登录')
    router.push({
      path: '/login',
      query: { redirect: router.currentRoute.value.fullPath }
    })
    return
  }

  // 跳转到商品详情页的评论区
  if (order.products && order.products.length > 0) {
    // 获取第一个商品的ID作为跳转目标
    const firstItem = order.products[0]
    const productId = firstItem.id
    
    if (!productId) {
      ElMessage.warning('无法获取商品ID')
      return
    }
    
    router.push({
      path: '/goods/detail',
      query: {
        id: productId,
        orderId: order.id,
        scrollToComment: 'true'
      }
    })
  } else {
    ElMessage.warning('没有找到可评价的商品')
  }
}

const handleBuyAgain = (order) => {
  // TODO: 实现再次购买功能
  ElMessage.info('再次购买功能开发中')
}

// 添加展开订单ID的响应式变量
const expandedOrderId = ref(null)

// 切换订单详情显示
const toggleOrderDetail = (orderId) => {
  if (expandedOrderId.value === orderId) {
    // 如果已经展开，则收起
    expandedOrderId.value = null
  } else {
    // 如果未展开，则展开
    expandedOrderId.value = orderId
  }
}

// 跳转到订单详情页
const handleOrderDetail = (order) => {
  router.push(`/orders/${order.id}`)
}

// 初始化
onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.user-orders {
  width: 100%;
}

.order-card {
  margin-bottom: 20px;
}

.card-header {
  margin-bottom: -20px;
}

.card-header h3 {
  margin: 0 0 20px 0;
}

.order-list {
  min-height: 300px;
}

.order-item {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  margin-bottom: 20px;
}

.order-header {
  padding: 15px;
  background-color: var(--el-fill-color-lighter);
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.order-status-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.order-status {
  color: var(--el-color-primary);
  font-weight: bold;
}

.payment-status {
  color: var(--el-color-success);
  font-weight: bold;
}

.order-content {
  padding: 20px;
}

.product-list {
  margin-bottom: 20px;
}

.product-item {
  display: flex;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.product-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-info h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
}

.product-spec {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin: 0 0 8px 0;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 15px;
}

.price {
  color: var(--el-color-danger);
  font-weight: bold;
}

.count {
  color: var(--el-text-color-secondary);
}

.total-price {
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.total-amount {
  font-size: 14px;
}

.amount {
  color: var(--el-color-danger);
  font-size: 18px;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.product-preview {
  cursor: pointer;
  padding: 10px 0;
}

.product-names {
  font-size: 14px;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  cursor: pointer;
}

.preview-more {
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

.order-detail {
  border-top: 1px solid var(--el-border-color-lighter);
  margin-top: 15px;
  padding-top: 15px;
}

.order-summary {
  margin-top: 20px;
  padding: 15px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 4px;
}

.summary-item {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 8px;
  color: var(--el-text-color-regular);
}

.summary-item.total {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid var(--el-border-color-lighter);
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.summary-item .amount {
  color: var(--el-color-danger);
  font-size: 18px;
  margin-left: 10px;
}
</style>